package com.baiyinet.ui;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiyinet.BuildConfig;
import com.baiyinet.R;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.rest.Link;
import com.baiyinet.ui.main.MainActivity_;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.Utils;
import com.baiyinet.util.webview.WebViewManager;
import com.github.ybq.android.spinkit.SpinKitView;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action0;

/**
 * @author J.Huang
 * @version 1.0
 * @since 16/11/14
 */

public abstract class BaseToolbarFragment extends Fragment implements ToolbarOwner.IToolbar {

    protected Toolbar mToolbar;
    protected TextView mToolbarTitle;
    protected View mToolbarBottomLine;
    protected WebView mWebView;
    protected RelativeLayout mRLayoutWebView;

    protected ToolbarOwner mToolbarOwner;

    protected List<ToolbarOwner.MenuAction> mActionBarMenuActionList;

    protected LinearLayout mLayoutWebView;
    protected WebViewManager mWebViewManager;

    private String mInitUrl;

    public View networkFailedView;

    public String lastValidUrl = "";

    abstract protected void findViews();

    protected void initData(final PageStatus pageStatus) {

        networkFailedView = View.inflate(getActivity(), R.layout.view_network_failed,null);
        networkFailedView.setVisibility(View.GONE);

        Button btnRetry = (Button) networkFailedView.findViewById(R.id.failed_btn_retry);
        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebViewManager != null) {
                    mWebViewManager.loadUrl(mInitUrl);
                }
            }
        });

        if (pageStatus == null) {
            return;
        }

        final SpinKitView loadingIndicator = (SpinKitView) getActivity().findViewById(R.id.view_loading_indicator);

//        mWebView = (WebView) getActivity().findViewById();
        mWebView = new WebView(getActivity().getApplicationContext());

        findViews();

        if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
//            mLayoutWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);

        mToolbarOwner = new ToolbarOwner(this);
        mWebViewManager = new WebViewManager(this, this, mWebView, loadingIndicator, ((MainActivity_) getActivity()).getCurrentUser(), ((MainActivity_) getActivity()).getApiHelper());
        mWebViewManager.init();
        mWebViewManager.loadUrl(pageStatus.url);

        if ("light".equals(BuildConfig.TOOLBAR_BACK)) {
            mToolbarTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
        } else {
            mToolbarTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.toolbar_title));
        }

        if (BuildConfig.SHOW_TOOLBAR_BOTTOM_LINE) {
            mToolbarBottomLine.setVisibility(View.VISIBLE);
        } else {
            mToolbarBottomLine.setVisibility(View.GONE);
        }

        if (!pageStatus.toolbarVisible) {
            mToolbar.setVisibility(View.GONE);
        } else {

            List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

            if (!TextUtils.isEmpty(pageStatus.menuName)) {
                ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction(pageStatus.menuName, new Action0() {
                    @Override
                    public void call() {
                        String url;
                        if (pageStatus.menuUrl.startsWith("http")) {
                            url = pageStatus.menuUrl;
                        } else {
                            url = BuildConfig.ENDPOINT + pageStatus.menuUrl;
                        }

                        Uri uri = Uri.parse(url);
                        String addLinkName = "";
                        String addLinkUrl = "";
                        String addLinkCode = uri.getQueryParameter("AddLink");
                        if (addLinkCode != null) {
                            if (getActivity() instanceof MainActivity_) {
                                List<Link> addLinkList = ((MainActivity_) getActivity()).getCurrentUser().getAddLinkList();
                                for (Link addLink : addLinkList) {
                                    if (addLink.Code.equals(addLinkCode)) {
                                        addLinkName = addLink.Name;
                                        addLinkUrl = addLink.Url;
                                        break;
                                    }
                                }
                            }
                        }

                        PageStatus newPageStatus = new PageStatus(url, true, true, addLinkName, addLinkUrl, pageStatus.toolbarBgColor);

                        IntentUtils.toNewGeneralActivity(BaseToolbarFragment.this, newPageStatus);
                    }
                }, R.drawable.ic_add);

                menuActionList.add(menuAction);
            }

            ToolbarOwner.Config config = new ToolbarOwner.Config("", false, menuActionList, pageStatus.toolbarBgColor);
            mToolbarOwner.setConfig(config);
        }

        mInitUrl = pageStatus.url;
    }

    protected boolean mReloaded = false;

    @Override
    public void onResume() {
        super.onResume();
        mWebViewManager.resume();
        if (mWebView != null) {
            mWebView.resumeTimers();
        }
        mReloaded = false;
        checkWebView();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 按情况开启，如果页面数据很多就不开启，避免载入失败
        mWebViewManager.pause();
        if (mWebView != null) {
            mWebView.pauseTimers();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mToolbar = null;
        mToolbarTitle = null;
        mToolbarOwner = null;

        mLayoutWebView.removeAllViews();

        // mWebViewManager有this的引用，必须清空
        mWebViewManager.destroy();
        mWebViewManager = null;

        if (mActionBarMenuActionList != null) {
            mActionBarMenuActionList.clear();
        }

        super.onDestroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (!Utils.Network.isNetworkAvailable()) {
                if (networkFailedView != null) {
                    networkFailedView.setVisibility(View.VISIBLE);
                }
                mWebViewManager.reload();
            }

            ((MainActivity_) getActivity()).refreshCurrentTabIndex();
            if (TextUtils.isEmpty(mWebView.getUrl())) {
                mWebViewManager.loadUrl(mInitUrl);
            }else {
                mWebViewManager.reload();
            }

        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (mToolbar != null) {
            Menu toolbarMenu = mToolbar.getMenu();
            toolbarMenu.clear();
            if (mActionBarMenuActionList != null && mActionBarMenuActionList.size() > 0) {
                for (final ToolbarOwner.MenuAction menuAction : mActionBarMenuActionList) {
                    toolbarMenu.add(menuAction.title)
                            .setIcon(menuAction.icon)
                            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
                            .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    menuAction.action.call();
                                    return true;
                                }
                            });
                }
            }
        }
//        inflater.inflate(R.menu.menu, menu);
//        mToolbar.inflateMenu(R.menu.menu);
//        mToolbar.setMenu();
//        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == android.R.id.home) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setToolbarTitle(CharSequence title) {
        if (getActivity() != null
                && ((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            // 默认title居左，不使用
            ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("");
            mToolbarTitle.setText(title);
        }
    }

    @Override
    public String getToolbarTitle() {
        String title = "";

        if (getActivity() != null
                && ((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            title = mToolbarTitle.getText().toString();
        }

        return title;
    }

    public WebView getWebView() {
        return mWebView;
    }

    /***
     * 使左上角程序图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标
     * 对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
     * @param enabled
     */
    @Override
    public void setDisplayShowHomeEnabled(boolean enabled) {
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    /***
     *  给左上角图标的左边加上一个返回的图标。对应ActionBar.DISPLAY_HOME_AS_UP
     * @param enabled
     */
    @Override
    public void setUpButtonEnabled(boolean enabled) {
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            // setHomeButtonEnabled和setDisplayShowHomeEnabled共同起作用。
            // 如果setHomeButtonEnabled设成false，
            // 即使setDisplayShowHomeEnabled设成true，图标也不能点击
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
            // setHomeButtonEnabled 小于4.0版本的默认值为true; 但是在4.0及其以上是false
            // 该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。true: 图标可以点击; false: 不可以点击。
            ((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(enabled);
        }
    }

    @Override
    public void setNavigationIcon(int resId) {
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null && resId != 0) {
            mToolbar.setNavigationIcon(null);
        }
    }

    @Override
    public void setMenu(List<ToolbarOwner.MenuAction> menuActionList) {
        if (menuActionList != mActionBarMenuActionList) {
            mActionBarMenuActionList = menuActionList;
            getActivity().invalidateOptionsMenu();
            getActivity().supportInvalidateOptionsMenu();
        }
    }

    @Override
    public void setToolbarVisible(boolean visible) {
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            if (visible) {
                ((AppCompatActivity) getActivity()).getSupportActionBar().show();
            } else {
                ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
            }
        }

//        if (visible) {
//            mToolbar.setVisibility(View.VISIBLE);
//        } else {
//            mToolbar.setVisibility(View.GONE);
//        }
    }

    @Override
    public void setToolbarColor(String hexColor) {
        if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
            if (!TextUtils.isEmpty(hexColor)) {
                if (hexColor.startsWith("#")) {
                    hexColor = hexColor.substring(1);
                }

                if (hexColor.length() != 6 && hexColor.length() != 8) {
                    ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getContext(), R.color.theme)));
                    return;
                }

                StringBuilder sb = new StringBuilder();
                sb.append("#");
                if (hexColor.length() == 6) {
                    sb.append("FF");
                    sb.append(hexColor);
                } else if (hexColor.length() == 8) {
                    sb.append(hexColor);
                }

                ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(sb.toString())));
            } else {
                ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getContext(), R.color.theme)));
            }
        }
    }

    public abstract void checkWebView();

    public abstract void reloadWebView();

    public void loadUrl(String url) {
        mWebViewManager.loadUrl(url);
    }

    public String getCurrentPageName() {
        return mWebViewManager.getCurrentPageName();
    }

}
